package com.github.pig.admin.controller;

import com.github.pig.admin.model.FrontInfoScspVo;
import com.github.pig.admin.model.ScspOpinionVo;
import com.github.pig.admin.model.TaskVo;
import com.github.pig.admin.service.ProcessService;
import com.github.pig.admin.util.ReType;
import com.github.pig.admin.util.Result;
import com.github.pig.admin.util.ResultCode;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngineConfiguration;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping(value = "/process/")
public class ScspProcessController {

	@Autowired
	private RuntimeService runtimeService;

    @Autowired
    private RepositoryService repositoryService;
    
    @Autowired
    private HistoryService historyService;

    @Autowired
    private ProcessEngineFactoryBean processEngine;

    @Autowired
    private ProcessEngineConfiguration processEngineConfiguration;
    @Autowired
    private ProcessService processService;
    
    /**
     * 跳转审查审批流程页面
     * @param
     * @return
     */
    @GetMapping(value = "showScsp")
    public String showScsp() {
      return "/act/scsp/scspList";
    }
    /**
     * 贷款申请编辑信息
     * @return
     */
    @GetMapping(value = "editScsp")
    public String editScsp() {
      return "/act/scsp/editScsp";
    }
    /**---------我的任务---------*/
    @GetMapping(value = "showTask")
    public String showTask(Model model){
      return "/act/task/taskList";
    }
    @GetMapping(value = "showCompleteTask")
    public String showCompleteTask(Model model){
        return "/act/task/showCompleteTask";
    }

    /**
     * 提交审查审批授信流程
     * @return
     */
    @PostMapping(value = "addScspProcess")
    @ResponseBody
    public Result addScsp(@RequestBody FrontInfoScspVo frontInfoScspVo){
        return processService.StartProcess(frontInfoScspVo);
    }
    /**
     * 查询任务列表
     * @param task
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "showTaskList")
    @ResponseBody
    public ReType showTaskList(TaskVo task, String page, String limit) {
      return processService.showTaskList(task, page, limit);
    }
    /**
     * 跳转审批办理页面
     * @param model
     * @param taskId
     * @return
     */
    @GetMapping("agent/{id}/{taskName}")
    public String agent(Model model, @PathVariable("id") String taskId, @PathVariable("taskName") String taskName){
      model.addAttribute("taskId",taskId);
      model.addAttribute("taskName",taskName);
      return "/act/task/task-agent";
    }

    
    /**
     * 追踪图片成图
     * @param
     * @param resp
     * @param processInstanceId
     * @throws IOException
     */
    @GetMapping("getProcImage")
    public void getProcImage(HttpServletResponse resp, String processInstanceId)
        throws IOException {
      ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      HistoricProcessInstance historicProcessInstance =
              historyService.createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
      String processDefinitionId=null;
      List<String> executedActivityIdList = new ArrayList<String>();
      if(processInstance!=null){
        processDefinitionId=processInstance.getProcessDefinitionId();
        executedActivityIdList=this.runtimeService.getActiveActivityIds(processInstance.getId());
      }else if(historicProcessInstance!=null){
        processDefinitionId=historicProcessInstance.getProcessDefinitionId();
        List<HistoricActivityInstance> historicActivityInstanceList =
                historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstanceId).orderByHistoricActivityInstanceId().asc().list();
        for (HistoricActivityInstance activityInstance : historicActivityInstanceList) {
          executedActivityIdList.add(activityInstance.getActivityId());
        }
      }

      if(StringUtils.isEmpty(processDefinitionId)||executedActivityIdList.isEmpty()){
        return;
      }
      BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);
      processEngineConfiguration = processEngine.getProcessEngineConfiguration();
      Context.setProcessEngineConfiguration((ProcessEngineConfigurationImpl) processEngineConfiguration);
      ProcessDiagramGenerator diagramGenerator = processEngineConfiguration.getProcessDiagramGenerator();
      InputStream imageStream=diagramGenerator.generateDiagram(
          bpmnModel, "png",
              executedActivityIdList, Collections.<String>emptyList(),
          processEngine.getProcessEngineConfiguration().getActivityFontName(),
          processEngine.getProcessEngineConfiguration().getLabelFontName(),
          "宋体",
          null, 1.0);
      byte[] b = new byte[1024];
      int len;
      while ((len = imageStream.read(b, 0, 1024)) != -1) {
        resp.getOutputStream().write(b,0,len);
      }
    }

    /**
     * 完成任务
     */
    @GetMapping(value = "completeTask")
    @ResponseBody
    public Result complete(ScspOpinionVo op) {
        Result result = new Result();
        try{
            processService.complete(op);
            result.setCode(ResultCode.SUCCESS);
        }catch (Exception E){
            result.setCode(ResultCode.FAIL);
        }

        return result;
    }

    /**
     * 根据受理人查询已办任务列表
     * @param page
     * @param limit
     * @return
     */
    @GetMapping(value = "showCompleteTaskList")
    @ResponseBody
    public ReType showCompleteTaskList(ScspOpinionVo opinionVo, String page, String limit) {
        return processService.showCompleteTaskList(opinionVo, page, limit);
    }

    /**
     * 回退任务
     */
    @GetMapping(value = "taskBack")
    @ResponseBody
    public Result taskBack(ScspOpinionVo op) {
        Result result = new Result();
        try{
            processService.taskBack(op);
            result.setCode(ResultCode.SUCCESS);
        }catch (Exception E){
            result.setCode(ResultCode.FAIL);
        }

        return result;
    }

}
